<template>
  <view class="services-manage">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <uni-easyinput
        v-model="searchKey"
        placeholder="搜索服务名称"
        :clearable="true"
      />
      <button type="primary" @click="handleAdd">新增服务</button>
    </view>

    <!-- 服务列表 -->
    <view class="service-list">
      <uni-card v-for="service in serviceList" 
                :key="service.id"
                :title="service.title"
                :extra="getCategoryName(service.category_id)">
        <!-- 服务信息 -->
        <view class="service-info">
          <image v-if="service.image_url" 
                 :src="service.image_url" 
                 mode="aspectFill"
                 class="service-image"/>
          <view class="info-content">
            <view class="info-item">
              <text class="label">描述:</text>
              <text class="description">{{service.description || '暂无描述'}}</text>
            </view>
            <view class="info-item">
              <text class="label">创建时间:</text>
              <text>{{formatDate(service.created_at)}}</text>
            </view>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <template v-slot:actions>
          <view class="actions">
            <button size="mini" @click="handleEdit(service)">编辑</button>
            <button size="mini" type="warn" @click="handleDelete(service)">删除</button>
          </view>
        </template>
      </uni-card>
    </view>

    <!-- 分页器 -->
    <uni-pagination
      :total="total"
      :pageSize="pageSize"
      :current="currentPage"
      @change="handlePageChange"
    />

    <!-- 编辑/新增弹窗 -->
    <uni-popup ref="formPopup" type="dialog">
      <view class="form-popup">
        <view class="popup-title">{{editForm.id ? '编辑服务' : '新增服务'}}</view>
        <view class="form-content">
          <uni-forms ref="form" :modelValue="editForm" :rules="rules">
            <uni-forms-item label="服务名称" required>
              <uni-easyinput v-model="editForm.title" placeholder="请输入服务名称"/>
            </uni-forms-item>
            <uni-forms-item label="服务分类" required>
              <uni-data-select
                v-model="editForm.category_id"
                :localdata="categoryOptions"
                placeholder="请选择服务分类"
              />
            </uni-forms-item>
            <uni-forms-item label="服务描述">
              <uni-easyinput
                v-model="editForm.description"
                type="textarea"
                placeholder="请输入服务描述"
              />
            </uni-forms-item>
            <uni-forms-item label="服务图片">
              <uni-file-picker
                :value="fileList"
                fileMediatype="image"
                mode="grid"
                @select="handleImageSelect"
                ref="filePicker"
              />
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="popup-buttons">
          <button @click="$refs.formPopup.close()">取消</button>
          <button type="primary" @click="handleSubmit">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      searchKey: '',
      serviceList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      categoryOptions: [
        { value: 1, text: '家政服务' },
        { value: 2, text: '维修服务' },
        { value: 3, text: '教育培训' },
        { value: 4, text: '美容美发' },
        { value: 5, text: '健康医疗' },
        { value: 6, text: '宠物服务' }
      ],
      fileList: [],
      editForm: {
        id: null,
        title: '',
        category_id: '',
        description: '',
        image_url: ''
      },
      rules: {
        title: {
          rules: [{
            required: true,
            errorMessage: '请输入服务名称'
          }]
        },
        category_id: {
          rules: [{
            required: true,
            errorMessage: '请选择服务分类'
          }]
        }
      }
    }
  },
  
  onLoad() {
    this.getServiceList()
  },
  
  methods: {
    // 获取服务列表
    async getServiceList() {
      try {
        const res = await request({
          url: '/services',
          method: 'GET',
          data: {
            page: this.currentPage,
            page_size: this.pageSize,
            keyword: this.searchKey
          }
        })
        if(res.data.status === 'success') {
          this.serviceList = res.data.data.items
          this.total = res.data.data.pagination.total
        }
      } catch(e) {
        console.error('获取服务列表失败:', e)
        uni.showToast({
          title: '获取服务列表失败',
          icon: 'none'
        })
      }
    },
    
    // 新增服务
    handleAdd() {
      this.editForm = {
        id: null,
        title: '',
        category_id: '',
        description: '',
        image_url: ''
      }
      this.fileList = []
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
      this.$refs.formPopup.open()
    },
    
    // 编辑服务
    handleEdit(service) {
      this.editForm = { ...service }
      this.fileList = service.image_url ? [{
        url: service.image_url,
        name: 'service_image',
        type: 'image'
      }] : []
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
      this.$refs.formPopup.open()
    },
    
    // 删除服务
    handleDelete(service) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除服务 ${service.title} 吗？`,
        success: async (res) => {
          if(res.confirm) {
            try {
              const res = await request({
                url: `/services/${service.id}`,
                method: 'DELETE'
              })
              if(res.data.status === 'success') {
                uni.showToast({
                  title: '删除成功'
                })
                this.getServiceList()
              }
            } catch(e) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 提交表单
    async handleSubmit() {
      // 表单验证
      try {
        await this.$refs.form.validate()
      } catch(e) {
        console.error('表单验证失败:', e)
        return
      }
      
      try {
        // 构建提交数据
        const submitData = {
          title: this.editForm.title,
          category_id: Number(this.editForm.category_id), // 确保 category_id 是数字
          description: this.editForm.description || '',
          image_url: this.editForm.image_url || ''
        }

        const url = this.editForm.id ? 
          `/services/${this.editForm.id}` : 
          '/services'
        const method = this.editForm.id ? 'PUT' : 'POST'
        
        const res = await request({
          url,
          method,
          data: submitData
        })
        
        if(res.data.status === 'success') {
          uni.showToast({
            title: '保存成功'
          })
          this.$refs.formPopup.close()
          this.getServiceList()
        }
      } catch(e) {
        console.error('保存服务失败:', e)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    },
    
    // 图片选择回调
    async handleImageSelect(e) {
      const tempFilePath = e.tempFilePaths[0]
      try {
        const uploadRes = await request({
          url: '/upload',
          method: 'POST',
          data: {
            file: tempFilePath,
            type: 'image'
          }
        })
        
        if(uploadRes.data.status === 'success') {
          const { url } = uploadRes.data.data
          this.editForm.image_url = url
          this.fileList = [{
            url: url,
            name: 'uploaded_image',
            type: 'image'
          }]
          if (this.$refs.form) {
            this.$refs.form.validateField('image_url')
          }
        }
      } catch(e) {
        console.error('图片上传失败:', e)
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
      }
    },
    
    // 分页变化
    handlePageChange(e) {
      this.currentPage = e.current
      this.getServiceList()
    },
    
    // 获取分类名称
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.value === categoryId)
      return category ? category.text : '未知分类'
    },
    
    // 格式化日期
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },
    
    // 搜索服务
    handleSearch() {
      this.currentPage = 1 // 重置页码
      this.getServiceList()
    },
    
    // 返回按钮点击
    handleBack() {
      uni.navigateBack({
        url: '/pages/admin/index'
      })
    }
  }
}
</script>

<style lang="scss">
.services-manage {
  padding: 20rpx;
  
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    uni-easyinput {
      flex: 1;
      margin-right: 20rpx;
    }
  }
  
  .service-list {
    .service-info {
      display: flex;
      
      .service-image {
        width: 200rpx;
        height: 200rpx;
        margin-right: 20rpx;
        border-radius: 8rpx;
      }
      
      .info-content {
        flex: 1;
        
        .info-item {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          
          .label {
            width: 120rpx;
            color: #666;
          }
          
          .description {
            color: #333;
          }
        }
      }
    }
    
    .actions {
      display: flex;
      gap: 20rpx;
      
      button {
        margin: 0;
      }
    }
  }
  
  .form-popup {
    background: #fff;
    border-radius: 10rpx;
    padding: 30rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
    }
    
    .form-content {
      max-height: 60vh;
      overflow-y: auto;
    }
    
    .popup-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 30rpx;
      
      button {
        width: 45%;
      }
    }
  }
}
</style> 